/**
 * Alipay.com Inc.
 * Copyright (c) 2004-2013 All Rights Reserved.
 */
package com.h2o3.carmack.session;

import java.util.Map;

import org.glassfish.grizzly.websockets.WebSocket;

import com.google.common.collect.Maps;
import com.h2o3.carmack.message.Message;
import com.h2o3.carmack.message.MessageSerializer;

/**
 * @author chensheng
 * @version $Id: Session.java, v 0.1 12/6/13 10:50 PM chensheng Exp $
 */
public class Session {
    private String              sessionKey;

    private WebSocket           socket;

    private Map<String, Object> userData;

    private MessageSerializer   messageSerializer;

    public Session(String sessionKey, WebSocket socket, MessageSerializer messageSerializer) {
        this.sessionKey = sessionKey;
        this.socket = socket;
        this.messageSerializer = messageSerializer;
    }

    public String getSessionKey() {
        return sessionKey;
    }

    protected Map<String, Object> getUserData() {
        synchronized (this) {
            if (userData == null) {
                userData = Maps.newConcurrentMap();
            }
        }
        return userData;
    }

    public void put(String key, Object value) {
        getUserData().put(key, value);
    }

    public Object get(String key) {
        return getUserData().get(key);
    }

    protected WebSocket getSocket() {
        return socket;
    }

    public void sendMessage(Message message) {
        socket.send(messageSerializer.writeMessage(message));
    }

    public void broadcast(SessionGroup group, Message message) {
        group.broadcast(this, message);
    }

    protected MessageSerializer getMessageSerializer() {
        return messageSerializer;
    }
}
